package com.fjxd.flightNumber.web;

import com.fjxd.feign.clients.CityClient;
import com.fjxd.feign.clients.PlaneClient;
import com.fjxd.feign.pojo.City;
import com.fjxd.feign.pojo.Plane;
import com.fjxd.feign.result.DistanceCalculation;
import com.fjxd.feign.result.ViewResult;
import com.fjxd.flightNumber.pojo.FlightNumber;
import com.fjxd.flightNumber.pojo.vo.HotCityVo;
import com.fjxd.flightNumber.service.FlightNumberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/flightNumber")
public class FlightNumberController {
    @Autowired
    private FlightNumberService flightNumberService;
    @Autowired
    private CityClient cityClient;
    @Autowired
    private PlaneClient planeClient;

    @GetMapping()
    public List<FlightNumber> getFlightNumberAll() {
        return flightNumberService.list();
    }

    @GetMapping("/getplaneByFlightNumber/{pid}")
    public List<FlightNumber> getplaneByFlightNumber(@PathVariable Integer pid)
    {
        return flightNumberService.getplaneByFlightNumber(pid);
    }


    @GetMapping("/getFlightNumberByUpCityId/{upCityId}/{downCityId}")
    public List<FlightNumber> getFlightNumberByUpCityIdAndDownCityId(@PathVariable Integer upCityId, @PathVariable Integer downCityId, @RequestParam Integer startIndex, @RequestParam Integer size) {
        return flightNumberService.getFlightNumberByUpCityIdAndDownCity(upCityId, downCityId, startIndex, size);
    }

    @GetMapping("/getFlightNumberIdByDownCityId/{downCityId}")
    public List<FlightNumber> getFlightNumberIdByDownCityId(@PathVariable Integer downCityId) {
        return flightNumberService.getFlightNumberByDownCity(downCityId);
    }


    @GetMapping("/getFlightNumberIdByUpCityId/{upCityId}/{downCityId}")
    public List<Integer> getFlightNumberIdByUpCityId(@PathVariable Integer upCityId, @PathVariable Integer downCityId, @RequestParam Integer startIndex, @RequestParam Integer size) {
        return flightNumberService.getFlightNumberIdByUpCityId(upCityId, downCityId, startIndex, size);
    }


    @GetMapping("/getFlightNumberIdByDownCityId/{upCityId}/{downCityId}")
    public List<FlightNumber> getFlightNumberIdByDownCityId(@PathVariable Integer upCityId, @PathVariable Integer downCityId) {
        return flightNumberService.getFlightNumberIdByDownCityId(upCityId, downCityId);
    }


    @GetMapping("/{id}")
    public ViewResult getFlightNumberById(@PathVariable int id) {
        return ViewResult.success(cityClient.getCityById(id));
    }

    @GetMapping("/getFlightNumberIdByCity/{city1}&{city2}")
    public List<Integer> getFlightNumberIdByCity(@PathVariable String city1, @PathVariable String city2) {
        return flightNumberService.getFlightNumberIdByCity(city1, city2);
    }
    /*start 雷允斫写的出了问题来找我*/
    @GetMapping("/getById/{id}")
    public FlightNumber getFlightNumberById(@PathVariable Integer id) {
        return flightNumberService.getById(id);
    }

    @PostMapping(path = "/getManyMsg")
    public List<FlightNumber> getManyMsg(@RequestBody List<Integer> ids) {
        return flightNumberService.getManyMsg(ids);
    }


    @GetMapping("/getFlightNumberByPlaneId/{id}")
    public List<FlightNumber> getFlightNumberByPlaneId(@PathVariable Integer id){
        return flightNumberService.getFlightNumberByPlaneId(id);
    }

    @GetMapping("/getHotCity/{id}")
    public List<HotCityVo> getHotCity(@PathVariable Integer id){
        return flightNumberService.getHotCity(id);
    }
    @GetMapping("/getTicketByCity/{cityId}/{city}")
    private List<FlightNumber> getTicketByCity(@PathVariable Integer cityId,@PathVariable String city){
        return flightNumberService.getTicketByCity(cityId,city);
    }

    /*end*/


    @PostMapping()
    public ViewResult addFlightNumber(@RequestBody FlightNumber flightNumber){
        boolean flag = flightNumberService.save(flightNumber);
        return new ViewResult(ViewResult.Status.SUCCESS.getCode(), "新增成功！");
    }

    @PutMapping()
    public ViewResult updateFlightNumber(@RequestBody FlightNumber flightNumber) {
        boolean flag = flightNumberService.updateById(flightNumber);
        return new ViewResult(ViewResult.Status.SUCCESS.getCode(), "修改成功！");
    }

    @DeleteMapping("{id}")
    public ViewResult deleteFlightNumber(@PathVariable String id) {
        boolean flag = flightNumberService.removeById(id);
        return new ViewResult(ViewResult.Status.SUCCESS.getCode(), flag ? "删除成功！" : "删除失败！");
    }

    @GetMapping("getByFlight/{flightNumber}")
    public ViewResult getFlightNumberByFlightNumber(@PathVariable String flightNumber){
        FlightNumber fNumber =  flightNumberService.getFlightNumberByFlightNumber(flightNumber);
        return ViewResult.success(fNumber);
    }

    @GetMapping("getFlightNumberByUpCityAndDownCity/{upCity}/{downCity}")
    public ViewResult getFlightNumberByUpCityAndDownCity(@PathVariable String upCity,@PathVariable String downCity){
        List<FlightNumber> flightNumbers = flightNumberService.getFlightNumberByUpCityAndDownCity(upCity,downCity);
        return ViewResult.success(flightNumbers);
    }

    @PostMapping("/addAll")
    public void addAll(){
        List<City> cities = cityClient.getCityAll();//获取所有城市
        List<Plane> planes = planeClient.getPlaneAll();//获取所有飞机
        FlightNumber flightNumber = new FlightNumber();
        String flightNumberSting = "";
        int sum = 1;//航班号序号累加
        int num = 0;//飞机集合索引值累加
        //生成每一个城市都有到其它城市的航班，但距离必须大于200km
        List<String> number = new ArrayList<>();//将添加到数据库中的号号编号放入该集合，用于判断新生成的航班号与数据库的是否重复
        for (int i = 0; i < cities.size(); i++) {
            for (int j = 0; j < cities.size(); j++) {
                City city1 = cities.get(i);//起点城市
                City city2 = cities.get(j);//终点城市
                //通过两城市平均人流量决定每天的航班数量
                int xun = (int) Math.ceil(((city1.getTrafficWas()+city2.getTrafficWas())/15));
                xun = xun<1 ? 1 : xun;
                //限制流量低的机场航班号
                if (city1.getTrafficWas()<3||city2.getTrafficWas()<3) {
                    xun =1;
                    if (flightNumberService.getFlightNumberByUpCityAndDownCity(city1.getName(), city2.getName()).size() >= 1 ){
                        continue;
                    }
                }else if (city1.getTrafficWas()<8||city2.getTrafficWas()<8){
                    xun =1;
                    if (flightNumberService.getFlightNumberByUpCityAndDownCity(city1.getName(), city2.getName()).size() >= 2 ) {
                        continue;
                    }
                }
                for (int q = 0; q < xun; q++) {
                    //设置起飞时间段在8:00-16:00之间
                    int starTime = xun>1?480/(xun-1):480/xun;
                    starTime = starTime*q;//定义每段起始时间
                    int starTimeNumber = 8+starTime/60;
                    int starTimeH = 8+starTime/60;//每段起始时间小时数
                    int starTimeM = (starTime%60)/10;//每段起始时间分钟数
                    starTimeM = starTimeM*10;
                    String starTimeHStr = starTimeH<10? "0"+starTimeH : ""+starTimeH;
                    //通过工具类获取两城市的距离
                    double distance = DistanceCalculation.lantitudeLongitudeDist(city1.getLongitude(),city1.getDimensionality(),city2.getLongitude(),city2.getDimensionality());
                    if (distance>200){//距离大于200KM才生成航班
                        //限制航班号序号不能超出3位数
                        if (sum>=99){
                            sum = 1;
                        }
                        Plane plane = planes.get(num);
                        //获取当前飞机航空公司的所有地区值
                        String [] regions = plane.getAirlines().getRegion().split("、");
                        String region = regions[0];
                        //生成航班号：航空公司+航空公司地区值+终点城市地区值+序列号getCompanyLetter
                        flightNumberSting = plane.getAirlines().getLetter()+region+city2.getRegion()+(sum>=10? sum : ("0"+sum));
                        //判断生成的号编号是否重复，若重复则更改航班序号，直到不重复为止
                        xun: for (int j1 = 0; j1 < regions.length; j1++) {
                            xun1: for (int k = 0; k < 49; k++) {
                                boolean into = true;
                                xun2: for (int i1 = 0; i1 < number.size(); i1++) {
                                    if (flightNumberSting.equals(number.get(i1))){
                                        region = regions[j1];
                                        sum += 2;
                                        if (sum>=99){
                                            sum = 1;
                                        }
                                        flightNumberSting = plane.getAirlines().getLetter()+region+city2.getRegion()+(sum>=10? sum : ("0"+sum));
                                        into = false;
                                        continue xun1;
                                    }
                                    if (i1 == number.size()-1&&into){
                                        break xun;
                                    }
                                }
                                if (number.size() <= 98){
                                    break xun;
                                }
                            }
                        }
                        number.add(flightNumberSting);
                        double sailingTime = distance / plane.getSpeed();//航行时间：距离除以每小时飞行速度(km)
                        //将小数单位的时间转换成小时+分钟
                        String[] str = (""+sailingTime).split("\\.");
                        int h = Integer.parseInt(str[0]) + starTimeNumber;
                        if (Double.parseDouble("0."+str[1]) * 60 + starTimeM > 60){
                            ++h;
                        }
                        h = h<24?h:h-24;
                        int m = (int) ((Double.parseDouble("0."+str[1]) * 60 + starTimeM)%60);
                        flightNumber.setPId(plane.getId());//飞机id
                        flightNumber.setFlightNumber(flightNumberSting);//航班号
                        flightNumber.setAId(plane.getAId());//航空公司id
                        flightNumber.setCompany(plane.getAirlines().getName());//航空公司
                        flightNumber.setUpCityId(city1.getId());//起点城市Id
                        flightNumber.setUpCity(city1.getName());//起点城市
                        flightNumber.setUpAirportName(city1.getAirportName());//起点机场
                        flightNumber.setDownCityId(city2.getId());//终点城市Id
                        flightNumber.setDownCity(city2.getName());//终点城市
                        flightNumber.setDownAirportName(city2.getAirportName());//终点机场
                        flightNumber.setStarTime(starTimeHStr+":"+starTimeM);//起飞时间
                        flightNumber.setEndTime(h+":"+m);//降落时间
                        flightNumber.setSailingTime("0"+str[0]+":"+(int) (sailingTime*60%60));//航行时间
                        flightNumber.setDistance((int) distance);//城市距离
                        flightNumber.setCompanyLogos(plane.getAirlines().getLogos());//公司logo
                        flightNumberService.save(flightNumber);
                        sum+=1;

                        //生成回航班
                        //生成航班号：航空公司+航空公司地区值+终点城市地区值+序列号
                        flightNumberSting = plane.getAirlines().getLetter()+region+city2.getRegion()+(sum>=10? sum : ("0"+sum));
                        double backTime = starTimeH + starTimeM/60.0 +sailingTime + 0.5;//回航起飞时间 :起飞时间 + 飞行时间 + 休息半小时时间
                        //将小数单位的时间转换成小时+分钟
                        String[] str1 = (""+backTime).split("\\.");
                        int h1 = Integer.parseInt(str1[0]);
                        int m1 = (int) (Double.parseDouble("0."+str1[1]) * 60);
                        double backTimeEnd = backTime + sailingTime;//回航到达时间：回航起飞时间 + 飞行时间
                        //将小数单位的时间转换成小时+分钟
                        String[] str2 = (""+backTimeEnd).split("\\.");
                        int h2 = Integer.parseInt(str2[0]);
                        h1 = h1<24?h1:h1-24;
                        h2 = h2<24?h2:h2-24;
                        int m2 = (int) (Double.parseDouble("0."+str2[1]) * 60);
                        flightNumber.setFlightNumber(flightNumberSting);//航班号
                        flightNumber.setUpCityId(city2.getId());//起点城市Id
                        flightNumber.setUpCity(city2.getName());//起点城市
                        flightNumber.setUpAirportName(city2.getAirportName());//起点机场
                        flightNumber.setDownCityId(city1.getId());//终点城市Id
                        flightNumber.setDownCity(city1.getName());//终点城市
                        flightNumber.setDownAirportName(city1.getAirportName());//终点机场
                        flightNumber.setStarTime((h1>=10 ? h1 : "0"+h1)+":"+m1);//起飞时间
                        flightNumber.setEndTime((h2>=10 ? h2 : "0"+h2)+":"+m2);//降落时间
                        flightNumber.setDistance((int) distance);//城市距离
                        flightNumberService.save(flightNumber);
                        num++;
                        sum+=1;
                    }
                }
            }

        }


    }
}
